import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/store_product_query.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/view_model.dart';

class StoreProductQueryModel extends ViewModel {
  final Api api;
  final int storeId;
  int _categoryId = 0; // 非null默认值。
  final int storeAreaId;
  final List<Product> _list = [];
  String _errorMessage;
  StoreProductQuery _storeProductQuery;

  StoreProductQueryModel(this.api, this.storeId, this.storeAreaId) : super();

  set categoryId(int value) {
    debugPrint('$this categoryId = $value');
    if (_categoryId != value) {
      _categoryId = value;
      _initData();
    }
  }

  List<Product> get list => _list;

  String get errorMessage => _errorMessage;

  StoreProductQuery get storeProductQuery => _storeProductQuery;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      _storeProductQuery = await api.storeProductQuery(
        storeId,
        _categoryId,
        storeAreaId,
        0,
        cancelToken,
      );
      _list.clear();
      _list.addAll(_storeProductQuery.productList);
      if (_list.isEmpty) {
        throw '暂无数据';
      }
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }

  Future<ViewState> loadData() async {
    try {
      _storeProductQuery = await api.storeProductQuery(
        storeId,
        _categoryId,
        storeAreaId,
        _list.length ~/ 10,
        cancelToken,
      );
      _list.addAll(_storeProductQuery.productList);
      viewState = ViewState.success;
    } catch (e) {}
    return viewState;
  }
}
